package cn.huiyunche.base.service.interfaces.impl;

import cn.huiyunche.base.service.constant.QiniuConstant;
import cn.huiyunche.base.service.framework.utils.QiniuUtils;
import cn.huiyunche.base.service.interfaces.AdminUserService;
import cn.huiyunche.base.service.interfaces.BannerService;
import cn.huiyunche.base.service.mappers.*;
import cn.huiyunche.base.service.model.*;
import cn.huiyunche.base.service.vo.Result;
import cn.huiyunche.tools.basic.exceptions.BusinessException;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 业务层
 *
 * @author hdy [Tuffy]
 */
@Service
public class BannerServiceImpl implements BannerService {

    private static final Logger LOGGER = LoggerFactory.getLogger(BannerServiceImpl.class);

    @Autowired
    private SysBannerMapper sysBannerMapper = null;

    @Autowired
    private SysAdminMenuMapper sysAdminMenuMapper = null;

    @Autowired
    private AdminUserService adminUserService = null;

    @Autowired
    private SysAdminMenuRoleMapper sysAdminMenuRoleMapper = null;

    @Autowired
    private SysAdminRoleUserMapper sysAdminRoleUserMapper = null;

    @Autowired
    private SysAdminBannerMapper sysAdminBannerMapper = null;

    public List<SysBanner> list(String clientType, String appType, String w, String h) throws Exception {
        LOGGER.info("list params : {}, {}, {}, {}", clientType, appType, w, h);
        String treatMethod = "1";
        SysBannerExample search = new SysBannerExample();
        SysBannerExample.Criteria criteria = search.createCriteria();
        if (StringUtils.isNotBlank(clientType)) {
            criteria.andClientTypeEqualTo(clientType);
        }
        if (StringUtils.isNotBlank(appType)) {
            criteria.andAppTypeEqualTo(appType);
        }
        List<SysBanner> banners = new ArrayList<SysBanner>();
        try {
            banners = this.getSysBannerMapper().selectByExample(search);
        } catch (Exception e) {
            LOGGER.error("selectByExample error : {}", e);
            throw new BusinessException("查询轮播图片错误");
        }
        if (StringUtils.isBlank(w) || StringUtils.isBlank(h)) {
            w = "";
            h = "";
            treatMethod = "";
        }
        if (CollectionUtils.isNotEmpty(banners) && banners.size() > 0) {
            for (SysBanner banner : banners) {
                banner.setPicKey(QiniuUtils.generateDownloadTicket(QiniuConstant.QINIU_DOWNLOAD_ADDRESS, banner.getPicKey(), treatMethod, w, h));
            }
        }
        return banners;
    }

    private SysBannerMapper getSysBannerMapper() {
        return this.sysBannerMapper;
    }

    /**
     * 获取我的banner
     *
     * @return
     */
    public Result<List<SysAdminBanner>> myBanner(Long bannerId) {
        LOGGER.info("myBanner param : {}", bannerId);
        Result<List<SysAdminBanner>> r = new Result<>(false);
        // 如果存在bannerId
//		if (null != bannerId) {
//			List<SysAdminBanner> list = new ArrayList<>();
//			list.add(this.getSysAdminBannerMapper().selectByPrimaryKey(bannerId));
//			r.setData(list);
//			r.setSuccess(true);
//			return r;
//		}
        List<SysAdminBanner> banners = new ArrayList<>();
        // 不是超级管理员，取出全部banner
        SysAdminBannerExample sabe = new SysAdminBannerExample();
        sabe.setOrderByClause("sort ASC");
        SysAdminBannerExample.Criteria criteria = sabe.createCriteria();
        // 根据用户ID查询角色
        SysAdminUser user = this.getAdminUserService().getThisUser();
        List<SysAdminRoleUser> sysAdminRoleUsers = sysAdminRoleUserByUserId(user.getId());
        if (CollectionUtils.isNotEmpty(sysAdminRoleUsers)) {
            SysAdminRoleUser adminRoleUser = sysAdminRoleUsers.get(0);
            List<SysAdminMenuRole> sysAdminMenuRoles = adminMenuRolesByRoleId(adminRoleUser.getRoleId());
            if (CollectionUtils.isNotEmpty(sysAdminMenuRoles)) {
                List<Long> adminMenuIds = sysAdminMenuRoles.stream().map(value -> value.getMenuId()).collect(Collectors.toList());
                List<SysAdminMenu> menus = menuListByMenuIds(adminMenuIds);
                if (CollectionUtils.isNotEmpty(menus)) {
                    List<Long> bannerIds = menus.stream().map(value -> value.getBannerId()).collect(Collectors.toList());
                    criteria.andIdIn(bannerIds);
                    banners = this.getSysAdminBannerMapper().selectByExample(sabe);
                }
            }
        }
        r.setData(banners);
        r.setSuccess(true);
        return r;
    }

    /**
     * 根据BannerIds查询Menus
     *
     * @param menuIds
     * @return
     */
    private List<SysAdminMenu> menuListByMenuIds(List<Long> menuIds) {
        if (CollectionUtils.isNotEmpty(menuIds)) {
            SysAdminMenuExample example = new SysAdminMenuExample();
            example.createCriteria().andIdIn(menuIds);
            return this.getSysAdminMenuMapper().selectByExample(example);
        }
        return null;
    }

    /**
     * 根据MenuIds查询角色
     *
     * @param roleId
     * @return
     */
    private List<SysAdminMenuRole> adminMenuRolesByRoleId(Long roleId) {
        if (roleId != null) {
            SysAdminMenuRoleExample example = new SysAdminMenuRoleExample();
            example.createCriteria().andRoleIdEqualTo(roleId);
            return this.getSysAdminMenuRoleMapper().selectByExample(example);
        }
        return null;
    }

    /**
     * 根据角色Id查询用户
     *
     * @param userId
     * @return
     */
    private List<SysAdminRoleUser> sysAdminRoleUserByUserId(Long userId) {
        if (userId != null) {
            SysAdminRoleUserExample example = new SysAdminRoleUserExample();
            example.createCriteria().andUserIdEqualTo(userId);
            return this.getSysAdminRoleUserMapper().selectByExample(example);
        }
        return null;
    }

    /**
     * 按id查询banner
     *
     * @return
     */
    public Result<SysAdminBanner> myBannerById(Long id) {
        LOGGER.info("myBannerById param : {}", id);
        Result<SysAdminBanner> r = new Result<>(true);
        r.setData(this.getSysAdminBannerMapper().selectByPrimaryKey(id));
        return r;
    }

    /**
     * 按id查询banner
     *
     * @return
     */
    public Result<String> saveMyBanner(SysAdminBanner sab) {
        LOGGER.info("saveMyBanner param : {}", sab);
        Result<String> r = new Result<>(false);
        // 修改
        Long id = sab.getId();
        if (null != id) {
            SysAdminBanner sabBean = this.getSysAdminBannerMapper().selectByPrimaryKey(id);
            if (null == sabBean) {
                r.setMessage("当前记录不存在");
                return r;
            }
            if (StringUtils.isBlank(sab.getTitle())) {
                r.setMessage("标题不可为空");
                return r;
            }
            this.getSysAdminBannerMapper().updateByPrimaryKeySelective(sab);
            r.setSuccess(true);
            return r;
        }
        // 新增
        if (StringUtils.isBlank(sab.getTitle())) {
            r.setMessage("标题不可为空");
            return r;
        }
        this.getSysAdminBannerMapper().insertSelective(sab);
        r.setSuccess(true);
        return r;
    }


    /**
     * 获取所有的banner
     *
     * @return
     */
    public Result<List<SysAdminBanner>> allBanner() {
        Result<List<SysAdminBanner>> r = new Result<>(true);
        SysAdminBannerExample sabe = new SysAdminBannerExample();
        sabe.createCriteria();
        sabe.setOrderByClause("sort ASC");
        r.setData(this.getSysAdminBannerMapper().selectByExample(sabe));
        return r;
    }

    private SysAdminBannerMapper getSysAdminBannerMapper() {
        return this.sysAdminBannerMapper;
    }

    private SysAdminMenuMapper getSysAdminMenuMapper() {
        return this.sysAdminMenuMapper;
    }

    private AdminUserService getAdminUserService() {
        return this.adminUserService;
    }

    private SysAdminMenuRoleMapper getSysAdminMenuRoleMapper() {
        return this.sysAdminMenuRoleMapper;
    }

    private SysAdminRoleUserMapper getSysAdminRoleUserMapper() {
        return this.sysAdminRoleUserMapper;
    }
}
